
/******************************************************************************/
/*     chaotix_pointer.cpp      Functions for the pointers within Chaotix     */
/*                              By: Josh Fiorio                               */
/******************************************************************************/

#include "chaotix_pointer.h"

extern FILE *ROM;           /* TODO: make functions get passed a file argument */
extern int rom_pos;         /* TODO: somehow get passed this to the funcs. as well */

void InitPointer(pointer &it, long address)
{
	//set the address
	it.address = address;

	//declare vars
    int pointon = 0;

    //go to where it points to
	rewind(ROM);
    //fseek(ROM, it.address, 0);
        rom_pos = it.address;
    
getnext:
	
	fseek(ROM, rom_pos, 0);

	//get pointer at that pos
	fread(&it.pointsto[pointon], 4/*sizeof(it.pointsto[pointon])*/, 1, ROM);
        rom_pos = rom_pos + 4/*sizeof(it.pointsto[pointon])*/;
    
    //next pointer
    if (it.pointsto[pointon] == 0xFFFFFFFF)
	{
        it.pointsto[pointon] = it.pointsto[0];
        pointon++;

        goto getnext;
    }	//end if

    //ok, change to big endian
    it.pointsto[pointon] = jntohl(it.pointsto[pointon]);
    if ((it.pointsto[pointon] & 0xFF000000) == 0xFF000000) { it.pointsto[pointon]=0; goto endit; }
    it.pointsto[pointon] = it.pointsto[pointon] - 0x2000000;
    if (it.pointsto[0] == rom_pos) { goto endit; }
	if (pointon == 128) { goto endit; }
    pointon++;
    goto getnext;
    
endit:
	int end = 0;
}	//end of func.



void WritePointer(pointer &it, int pointed)
{
	//declare vars.
	long newval = jhtonl(it.pointsto[pointed] + 0x2000000);
    int posplus = pointed * 4;
    
	//goto pos in rom of pointer
    rom_pos = it.address + (pointed*4);
	fseek(ROM, rom_pos, 0);

	//write new ptr.
	fwrite(&newval, sizeof(newval), 1, ROM);
		rom_pos = rom_pos + sizeof(newval);
		fseek(ROM, rom_pos, 0);
}	//end of func.
